package com.bbcare.switchData.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.*;
import com.bbcare.followup.plat.service.IFollowQueueService;
import com.bbcare.followup.plat.service.IPatientService;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.HashMap;

/**
 * @Title		PlatFormController.java
 * @Package		com.bbcare.switchData.controller
 * @Description	提供给宣教平台对接
 * @Author		<a href="mailto:jiangqian_java@163.com">jiang</a>
 * @Date		2023/3/28
 * @Version		V1.0 
 * @Copyright	(c) Shanghai BBcare Medical Equipment Co.,Ltd.
 */
@RestController
@RequestMapping(value="/platform/education")
public class PlatFormEducationController {

    private final Log logger = LogFactory.getLog(PlatFormEducationController.class);

    @Autowired
    private IPatientService patientSerivce;

    @Autowired
    private IFollowQueueService followQueueSerivce;

    // 患者信息List查询
    @ResponseBody
    @RequestMapping("/patientQueueListQuery")
    public ResultModel<HashMap<String, Object>> qryPatientQueueSchemeList(@RequestBody String arg,
                                                                          HttpServletRequest request) throws Exception {
        logger.warn("in qryPatientQueueSchemeList----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        HashMap<String, Object> paramMap = new HashMap<String, Object>();

        String authorId = "0";
        String tenantId = jsonData.getString("tenantId");

        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);

        Integer ageTo = jsonData.getInteger("ageTo");
        Integer ageFrom = jsonData.getInteger("ageFrom");

        Calendar to = Calendar.getInstance();
        if (ageTo != null) {
            to.add(Calendar.MONTH, -ageTo);
            paramMap.put("ageTo", DateUtil.getDate_8(to.getTime()));
        }

        Calendar from = Calendar.getInstance();
        if (ageFrom != null) {
            from.add(Calendar.MONTH, -ageFrom);
            // from.set(Calendar.DAY_OF_MONTH,
            // from.getActualMaximum(Calendar.DAY_OF_MONTH));
            paramMap.put("ageFrom", DateUtil.getDate_8(from.getTime()));
        }

        String flag = jsonData.getString("flag");
        if (null == flag || "".equals(flag)) {
            // 默认查询当日待随访的患者
            flag = "0";
        }
        String phoneNo = jsonData.getString("phoneNum");
        String userName = jsonData.getString("patientName");// 可以是姓氏或姓名
        String hisNo = jsonData.getString("hisNo");// 科研编号
        String fuzzyVar = jsonData.getString("fuzzyVar");// 姓名或科研编号
        if (!StringUtils.isEmpty(fuzzyVar)) {
            paramMap.put("fuzzyVar", fuzzyVar.replace(" ", "") + "%");
        }
        int page = jsonData.getIntValue("page");
        int rows = jsonData.getIntValue("rows");
        page = page == 0 ? 1 : page;
        rows = rows == 0 ? 20 : rows;

        if (!StringUtils.isEmpty(phoneNo)) {
            paramMap.put("phoneNo", phoneNo);
        }
        if (!StringUtils.isEmpty(userName)) {
            paramMap.put("userName", userName);
            //增加通过拼音查询用户
            paramMap.put("namePinyin", userName.toLowerCase() + "%");
            //名字简拼
            paramMap.put("nameInitial", userName.toLowerCase() + "%");
        }
        paramMap.put("flag", flag);
        paramMap.put("start", (page - 1) * rows);
        paramMap.put("end", rows);

        // 增加队列id和患者来源
        paramMap.put("queueId", jsonData.getString("queueId"));
        paramMap.put("sourceType", jsonData.getString("opType"));
        paramMap.put("premature", jsonData.getString("premature"));
        paramMap.put("qryEndTime", jsonData.getString("qryEndTime"));
        paramMap.put("qryStartTime", jsonData.getString("qryStartTime"));
        if (!StringUtils.isEmpty(hisNo)) {
            paramMap.put("hisNo", hisNo);
        }
        // 可以查询队列中正常状态患者，也可查询扫码建档待审核状态的患者
        String confirmFlag = jsonData.getString("confirmFlag");
        if (StringUtils.isNotEmpty(confirmFlag)) {
            paramMap.put("confirmFlag", confirmFlag);
        }
        paramMap.put("systemType", jsonData.getString("systemType"));// 系统类型，00随访，01诊疗
        paramMap.put("taskAuditStatus", jsonData.getString("taskAuditStatus"));

        // 针对Datatable特殊处理
        String jsonStr = jsonData.getString(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (!StringUtils.isEmpty(jsonStr)) {
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonStr);
            draw = jsonTable.getIntValue("draw");
            paramMap.put("start", jsonTable.getIntValue("start"));
            paramMap.put("end", jsonTable.getIntValue("length"));
        }

        // 特殊处理一妇婴倍力多项目
        paramMap.put("showFlag", jsonData.getString("showFlag"));
        long time = System.currentTimeMillis();
        HashMap<String, Object> retMap = patientSerivce.qryPatientQueueSchemeList(paramMap);
        long time2 = System.currentTimeMillis();
        System.out.println("ceshi1789  : " + (time2 - time));
        // 针对Datatable特殊处理
        if (!StringUtils.isEmpty(jsonStr)) {
            retMap.put("draw", draw);
            retMap.put("recordsTotal", retMap.get("total"));
            retMap.put("recordsFiltered", retMap.get("total"));
        }

        return new ResultModel<HashMap<String, Object>>(retMap);
    }

    // 队列信息List查询
    @ResponseBody
    @RequestMapping("/followQueueListQuery")
    public ResultModel<HashMap<String, Object>> getFollowQueueList(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in getFollowQueueList----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参节点错误，非json格式！"));
        }
        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        JSONObject jsonData = jsonArg.getJSONObject("data");
        if (null == jsonData) {
            logger.warn("in getFollowQueueList----no data node...");
            // 前台必须传data节点，否则报错返回（后续重写异常类）
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        paramMap.putAll(jsonData);
        int page = jsonData.getIntValue("page");
        int rows = jsonData.getIntValue("rows");
        if (page > 0 && rows > 0) {
            paramMap.put("start", (page - 1) * rows);
            paramMap.put("end", rows);
        }

        String authorId = "0";
        String tenantId = jsonData.getString("tenantId");

        paramMap.put("authorId", authorId);
        paramMap.put("queueStatus", Constants.QUEUE_STATUS_NOMAL);
        paramMap.put("queueTypeTenant", Constants.QUEUE_TYPE_TENANT);
        paramMap.put("queueTypePublic", Constants.QUEUE_TYPE_PUBLIC);
        paramMap.put("queueTypePrivate", Constants.QUEUE_TYPE_PRIVATE);
        String objectStr = jsonData.getString("queueName");
        String queueName = StringUtils.isBlank(objectStr) ? objectStr : "%" + objectStr + "%";

        paramMap.put("queueName", queueName);
        if (null != tenantId) {
            paramMap.put("tenantId", tenantId.toString());
        }
        String showFlag = jsonData.getString("showFlag");
        if(!StringUtils.isBlank(showFlag)) {
            paramMap.put("showFlag", showFlag);
        }
        HashMap<String, Object> retOut = followQueueSerivce.getQueueList(paramMap);
        return new ResultModel<HashMap<String, Object>>(retOut);
    }




}
